package leetcode.code1425;

import java.util.LinkedList;
import java.util.Queue;

import leetcode.IDebug;
import leetcode.helper.H;

// 用单调栈，选择大数的贪心方式是错的。
public class Solution implements IDebug {

	public int constrainedSubsetSum(int[] nums, int k) {
		int ans = Integer.MIN_VALUE, L = -1, sum = -1;
		Queue<Integer> queue = new LinkedList<>();
		for (int i = 0; i < nums.length; i++) {
			if (i > L + k) {
				L = queue.poll();
				sum += nums[L];// sum < 0
			}
			while (!queue.isEmpty() && nums[i] >= nums[queue.peek()]) {
				queue.poll();
			}
			queue.add(i);
			if (!queue.isEmpty() && nums[queue.peek()] >= 0) {
				L = queue.poll();
				sum = sum < 0 ? nums[L] : sum + nums[L];
				ans = Math.max(ans, sum);
			}
			ans = Math.max(ans, nums[i]);
		}
		return ans;
	}

	@Override
	public void debug4() {
		H.compare(125,
				this.constrainedSubsetSum(H.str2array3("[100,-10,-10,-10,-2,-2,-10,-100,15,-5,-10,10,2,-10,5,20]"), 2));
		H.compare(23, this.constrainedSubsetSum(H.str2array3("[10,-2,-10,-5,20]"), 2));
		H.compare(37, this.constrainedSubsetSum(H.str2array3("[10,2,-10,5,20]"), 2));
		H.compare(-1, this.constrainedSubsetSum(H.str2array3("[-1,-2,-3]"), 2));
		H.compare(23, this.constrainedSubsetSum(H.str2array3("[10,-2,-10,-5,20]"), 2));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
